const goodsCart = {
	state: {
		shopCart:{
			//id 商品编码 num 数量  pPrice 价格 checked 是否选择 
			items:[],
			totalMoney:0,
			totalNum:0
		}
	},
	mutations: {
		//增加或更新商品
		addToCart(state, goodsinfo) { //点击加入购物车,保存商品信息
			let cart =state.shopCart ;
			var flag = false; //假设没有新加入的商品
			cart.items.forEach(item => {
				if (item.id == goodsinfo.id) {//检测添加的商品是否和购物车里的商品一样
					item.num = parseInt(goodsinfo.num);
					flag = true;
					return true;
				}
			});
			if (!flag) { //添加到购物车
				cart.items.push(goodsinfo);
			}
			let tempTotalNum = 0;
			let tempTotalMoney = 0;
			cart.items.forEach(item => {
				console.log(item)
				tempTotalNum += item.num;
				tempTotalMoney += (item.price * 100) * item.num / 100;
			});
			cart.totalNum = tempTotalNum;
			cart.totalMoney = tempTotalMoney;
			//保存到本地存储
			// uni.setStorageSync('shopCart', JSON.stringify(cart));
		},
		delCart(state, goodsinfo) {
			let cart =state.shopCart ;
			cart.items.forEach((item, index) => {
				if (item.id == goodsinfo.id) {
					if(goodsinfo.num == 0){
						cart.items.splice(index,1)
					}else{
						item.num = parseInt(goodsinfo.num);
					}
				}
			});
			let tempTotalNum = 0;
			let tempTotalMoney = 0;
			cart.items.forEach(item => {
				tempTotalNum += item.num;
				tempTotalMoney += (item.price * 100) * item.num / 100;
			});
			cart.totalNum = tempTotalNum;
			cart.totalMoney = tempTotalMoney;
			//保存到本地存储
			// uni.setStorageSync('shopCart', JSON.stringify(cart));
		},
		//切换社区，清空伪购物车
		clearCart(state){
			let cart =state.shopCart ;
			cart.items = []
			cart.totalMoney = 0
			cart.totalNum=0
		}
		//更新选中状态
		// updateGoodsChecked(state, goodsinfo) {
		// 	let cart =state.shopCart ;
		// 	cart.items.some(item => {
		// 		if (item.produceCode == goodsinfo.produceCode) {
		// 			item.checked = goodsinfo.checked;
		// 		}
		// 	});
		// 	uni.setStorageSync('shopCart', JSON.stringify(cart));
		// },
		//全选/反选切换
		// updateAllGoodsChecked(state, boolean) {
		// 	let cart =state.shopCart ;
		// 	cart.items.forEach(item => {
		// 		item.checked = boolean;
		// 	});
		// 	uni.setStorageSync('shopCart', JSON.stringify(cart));
		// }
	},
	actions:{
		addCart(context,params){
			context.commit('addToCart',params)
		},
		delCart(context,params){
			context.commit('delCart',params)
		},
		clearnCart(context){
			context.commit('clearCart');
		}
	},
	getters:{
		getCartItem(state){
			return state.shopCart.items
		},
		getCartTotalMoney(state){
			return state.shopCart.totalMoney
		},
		getCartTotalNum(state){
			return state.shopCart.totalNum
		}
	}
}
export default goodsCart